/* *
 * @program: LivePublisher
 *
 * @description: ${description}
 *
 * @author: 909845
 *
 * @create: 2019-03-28 15:02
***/

#include "LivePublisherManager.h"
#include "../Public/PrintMacro.h"
#include "../Media/IRemuxInterface.h"
#include "../SendStream/SendToOVideoCDN.h"
#include "MediaRemux.h"
#include "LivePublisher.h"

#define TAG "MID[" << m_strManagerID << "]- "

CLivePublisherManager::CLivePublisherManager(const char *pManagerID) : m_strManagerID(pManagerID)
{
    TRACE_LOG(TAG << "Create LivePublisherManager");
}

CLivePublisherManager::~CLivePublisherManager()
{
    TRACE_LOG(TAG << "Destroy ~LivePublisherManager");
}

bool CLivePublisherManager::Initialize(Int32 nThreadCount, const int *pAffinity, int nAffinityLen)
{
    Assert(m_vecThreadPool.empty());
    Assert(0 == m_threadIndex);
    Assert(nThreadCount > 0);
    bool bRet = false;
    do
    {
        for (int i = 0; i < nThreadCount; ++i)
        {
            shared_ptr<CEventThread> spThread(new CEventThread());
            if (nullptr == pAffinity)
            {
                spThread->Initialize();
            }
            else
            {
                spThread->Initialize(pAffinity[i % nAffinityLen]);
            }
            m_vecThreadPool.push_back(spThread);
        }
        bRet = true;
    } while (0);

    return bRet;
}


ILivePublisher *CLivePublisherManager::CreateLivePublisher(const char *pStreamID, const char *pHost)
{
    ILivePublisher *pObj = nullptr;
    Assert(!m_vecThreadPool.empty());
    do
    {
        uint32_t nIndex = __sync_fetch_and_add(&m_threadIndex, 1) % m_vecThreadPool.size();
        shared_ptr<CLivePublisher> spLive(new CLivePublisher(m_strManagerID.c_str(), pStreamID, pHost, "/publish/locate", m_vecThreadPool[nIndex]));
        spLive->HoldMyself();
        pObj = spLive.get();
    } while (0);

    return pObj;
}

void CLivePublisherManager::Release()
{
    delete this;
}

ILivePublisherManager *CreateLivePublisherManager(const char *pManagerID)
{
    return new CLivePublisherManager(pManagerID);
}
